﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Text;
using System.Threading.Tasks;

namespace GGetTestService.Middleware
{
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionMiddleware> _logger;
        public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next.Invoke(context);
                var features = context.Features;
            }
            catch (Exception ex)
            {
                await HandleException(context, ex);
            }
        }

        private Task HandleException(HttpContext context, Exception ex)
        {
            #region 自定义

            StringBuilder sb = new StringBuilder();
            sb.Append(ex.Message);
            var stack = ex.StackTrace;
            sb.Append(stack);
            //var errorArrays = stack.Split(new string[1] { Environment.NewLine }, StringSplitOptions.None);
            //if (errorArrays.Length > 0)
            //{
            //    sb.Append("\n");
            //    foreach (var item in errorArrays)
            //    {
            //        sb.Append($"{item}{Environment.NewLine}");
            //    }
            //}
            return Task.Run(() => _logger.LogError(sb.ToString()));

            #endregion 自定义
        }
    }
}